<template>
  <div class="app-container">
    <div class="toatst" style="width: 100%;height: 100%;position: fixed; z-index: 9999; " v-if="loadToast">
      <i class="el-icon-loading" style="font-size: 60px; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #000;"></i>
    </div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资产编号" prop="meterNo">
        <el-input v-model="queryParams.meterNo" placeholder="请输入资产编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="条形码" prop="rfidNo">
        <el-input v-model="queryParams.rfidNo" placeholder="请输入条形码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="出厂编号" prop="madeNo">
        <el-input v-model="queryParams.madeNo" placeholder="请输入出厂编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="类别" prop="sortCode">
        <el-select v-model="queryParams.sortCode" placeholder="请选择类别" clearable>
          <el-option v-for="dict in dict.type.emi_meter_sort" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="typeCode">
        <el-input v-model="queryParams.typeCode" placeholder="请输入类型" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="业务状态" prop="serviceStatus">
        <el-select v-model="queryParams.serviceStatus" placeholder="请选择业务状态" clearable>
          <el-option v-for="dict in dict.type.service_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="当前状态" prop="curStatusCode">
        <el-select v-model="queryParams.curStatusCode" placeholder="请选择当前状态" clearable>
          <el-option v-for="dict in dict.type.cur_status_code" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="库房" prop="whId">
        <el-select v-model="queryParams.whId" placeholder="请选择库房" @change="whIdChange" clearable>
          <el-option v-for="dict in option" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="库区" prop="whAreaId">
        <el-select v-model="queryParams.whAreaId" placeholder="请选择库区" @change="whAreaIdChange" clearable>
          <el-option v-for="dict in options" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="存放区" prop="storeAreaId">
        <el-select v-model="queryParams.storeAreaId" placeholder="请选择存放区" @change="storeAreaIdChange" clearable>
          <el-option v-for="dict in messageOption" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="储位" prop="storeLocId">
        <el-select v-model="queryParams.storeLocId" placeholder="请选择储位" clearable>
          <el-option v-for="dict in storageOption" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="接线方式" prop="wiringMode">
        <el-select v-model="queryParams.wiringMode" filterable placeholder="请选择接线方式" clearable>
          <el-option v-for="dict in dict.type.md_wiring_mode" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="电压" prop="voltCode">
        <el-select v-model="queryParams.voltCode" filterable placeholder="请选择电压" clearable>
          <el-option v-for="dict in dict.type.md_volt_code" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="电流" prop="currentCode">
        <el-select v-model="queryParams.currentCode" filterable placeholder="请选择电流" clearable>
          <el-option v-for="dict in dict.type.md_current_code" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="有功等级" prop="apPreLevelCode">
        <el-select v-model="queryParams.apPreLevelCode" filterable placeholder="请选择有功等级" clearable>
          <el-option v-for="dict in dict.type.md_ap_pre_level_code" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['meter:mdMeter:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['meter:mdMeter:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['meter:mdMeter:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['meter:mdMeter:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['meter:mdMeter:export']">导出</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-sort" size="mini" @click="downloadData"
          v-hasPermi="['meter:mdMeter:downloadJsonMdMeter']">下载数据</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mdMeterList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="电能表标识" align="center" prop="meterId" min-width="90px" />
      <el-table-column label="条形码" align="center" prop="rfidNo" min-width="300px" />
      <el-table-column label="业务状态" align="center" prop="serviceStatus" min-width="100px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.service_status" :value="scope.row.serviceStatus" />
        </template>
      </el-table-column>
      <el-table-column label="当前状态" align="center" prop="curStatusCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cur_status_code" :value="scope.row.curStatusCode" />
        </template>
      </el-table-column>
      <el-table-column label="设备码" align="center" prop="equipCode" min-width="220px" />
      <el-table-column label="设备名称" align="center" prop="equipName" min-width="550px" />
      <el-table-column label="接线方式" align="center" prop="wiringMode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.md_wiring_mode" :value="scope.row.wiringMode" />
        </template>
      </el-table-column>
      <el-table-column label="电压" align="center" prop="voltCode" min-width="110px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.md_volt_code" :value="scope.row.voltCode" />
        </template>
      </el-table-column>
      <el-table-column label="电流" align="center" prop="currentCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.md_current_code" :value="scope.row.currentCode" />
        </template>
      </el-table-column>
      <el-table-column label="有功等级" align="center" prop="apPreLevelCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.md_ap_pre_level_code" :value="scope.row.apPreLevelCode" />
        </template>
      </el-table-column>
      <el-table-column label="资产编号" align="center" prop="meterNo" min-width="300px" />
      <!-- <el-table-column label="库房标识" align="center" prop="whId" v-if="false" />
      <el-table-column label="库房" align="center" prop="whName" min-width="340px" />
      <el-table-column label="库区标识" align="center" prop="whAreaId" v-if="false" />
      <el-table-column label="库区" align="center" prop="whAreaname" min-width="120px" />
      <el-table-column label="存放区标识" align="center" prop="storeAreaId" v-if="false" />
      <el-table-column label="存放区" align="center" prop="storeAreaName" min-width="110px" />
      <el-table-column label="储位标识" align="center" prop="storeLocId" v-if="false" />
      <el-table-column label="储位" align="center" prop="storeLocName" min-width="120px" /> -->
      <el-table-column label="出厂编号" align="center" prop="madeNo" min-width="115px" />
      <el-table-column label="类别" align="center" prop="sortCode" min-width="100px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.emi_meter_sort" :value="scope.row.sortCode" />
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="typeCode" min-width="200px" />
      <el-table-column label="型号" align="center" prop="modelCode" min-width="110px" />
      <el-table-column label="封印编号" align="center" prop="sealNo" min-width="200px" />
      <el-table-column label="表地址" align="center" prop="meterAddress" min-width="120px" />
      <el-table-column label="无功等级" align="center" prop="rpPreLevelCode" />
      <el-table-column label="是否双向计量" align="center" prop="bothWayCalc" min-width="100px" />
      <el-table-column label="电能表位数" align="center" prop="meterDigits" min-width="100px" />
      <el-table-column label="所在单位" align="center" prop="belongDept" min-width="330px" />
      <el-table-column label="产权单位" align="center" prop="prOrg" min-width="330px" />
      <el-table-column label="地区名称" align="center" prop="areaCode" min-width="275px" />
      <el-table-column label="产权" align="center" prop="prCode" min-width="110px" />
      <el-table-column label="制造单位" align="center" prop="manufacturer" min-width="250px" />
      <el-table-column label="到货批次" align="center" prop="lotNo" min-width="200px" />
      <el-table-column label="配送日期" align="center" prop="deliveryDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="建档日期" align="center" prop="createdDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检定入库日期" align="center" prop="inspectInDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inspectInDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="安装日期" align="center" prop="instDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.instDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="拆表日期" align="center" prop="rmvDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.rmvDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报废日期" align="center" prop="descardDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.descardDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="通讯规约" align="center" prop="commProtCode" min-width="110px" />
      <el-table-column label="波特率" align="center" prop="baudrateCode" />
      <el-table-column label="是否阻逆" align="center" prop="ccPreventFlag" />
      <el-table-column label="计度器方式" align="center" prop="registerMode" min-width="110px" />
      <el-table-column label="建档类型" align="center" prop="docTypeCode" />
      <el-table-column label="电能表技术规范版本" align="center" prop="versionNo" min-width="150px" />
      <el-table-column label="电价码" align="center" prop="tariffCode" />
      <el-table-column label="电价名称" align="center" prop="tariffName" />
      <el-table-column label="电价金额" align="center" prop="tariffAmount" />
      <el-table-column label="电价版本号" align="center" prop="tariffVersionNo" min-width="100px" />
      <el-table-column label="预置电费" align="center" prop="presetCharge" />
      <el-table-column label="订单类型" align="center" prop="orderType" />
      <el-table-column label="芯片厂商" align="center" prop="chipManufacturer" min-width="190px" />
      <el-table-column label="分拣日期" align="center" prop="sortingDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sortingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="资金来源" align="center" prop="capitalSource" />
      <el-table-column label="盘点时间" align="center" prop="checkDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.checkDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="绑定模块条码" align="center" prop="moduleCode" min-width="100px" />
      <el-table-column label="电表费率时段" align="center" prop="ratePeriod" min-width="100px" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" min-width="120px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['meter:mdMeter:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['meter:mdMeter:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改电能表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1160px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="条形码" prop="rfidNo">
              <el-input v-model="form.rfidNo" placeholder="请输入条形码" maxlength="50" />
              <!-- <el-button type="primary" size="mini" plain @click="cardReading">读卡</el-button>
              <el-button type="success" size="mini" plain @click="writeCard">写卡</el-button> -->
            </el-form-item>
          </el-col>
         <!-- <el-col :span="8">
            <el-form-item label="设备码" prop="equipCode">
              <el-input v-model="form.equipCode" placeholder="请输入设备码" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备名称" prop="equipName">
              <el-input v-model="form.equipName" placeholder="请输入设备名称" maxlength="50" />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="接线方式" prop="wiringMode">
              <el-select v-model="form.wiringMode" filterable placeholder="请选择接线方式" clearable>
                <el-option v-for="dict in dict.type.md_wiring_mode" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电压" prop="voltCode">
              <el-select v-model="form.voltCode" filterable placeholder="请选择电压" clearable>
                <el-option v-for="dict in dict.type.md_volt_code" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电流" prop="currentCode">
              <el-select v-model="form.currentCode" filterable placeholder="请选择电流" clearable>
                <el-option v-for="dict in dict.type.md_current_code" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="有功等级" prop="apPreLevelCode">
              <el-select v-model="form.apPreLevelCode" filterable placeholder="请选择有功等级" clearable>
                <el-option v-for="dict in dict.type.md_ap_pre_level_code" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出厂编号" prop="madeNo">
              <el-input v-model="form.madeNo" placeholder="请输入出厂编号" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类别" prop="sortCode">
              <el-select v-model="form.sortCode" placeholder="请选择类别" clearable>
                <el-option v-for="dict in dict.type.emi_meter_sort" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类型" prop="typeCode">
              <el-input v-model="form.typeCode" placeholder="请输入类型" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="型号" prop="modelCode">
              <el-input v-model="form.modelCode" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="封印编号" prop="sealNo">
              <el-input v-model="form.sealNo" placeholder="请输入封印编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="表地址" prop="meterAddress">
              <el-input v-model="form.meterAddress" placeholder="请输入表地址" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="无功等级" prop="rpPreLevelCode">
              <el-input v-model="form.rpPreLevelCode" placeholder="请输入无功等级" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否双向计量" prop="bothWayCalc">
              <el-input v-model="form.bothWayCalc" placeholder="请输入是否双向计量" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电能表位数" prop="meterDigits">
              <el-input v-model="form.meterDigits" placeholder="请输入电能表位数" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所在单位" prop="belongDept">
              <el-input v-model="form.belongDept" placeholder="请输入所在单位" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产权单位" prop="prOrg">
              <el-input v-model="form.prOrg" placeholder="请输入产权单位" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地区名称" prop="areaCode">
              <el-input v-model="form.areaCode" placeholder="请输入地区名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产权" prop="prCode">
              <el-input v-model="form.prCode" placeholder="请输入产权" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制造单位" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入制造单位" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="到货批次" prop="lotNo">
              <el-input v-model="form.lotNo" placeholder="请输入到货批次" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配送日期" prop="deliveryDate">
              <el-date-picker clearable v-model="form.deliveryDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择配送日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="建档日期" prop="createdDate">
              <el-date-picker clearable v-model="form.createdDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择建档日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检定入库日期" prop="inspectInDate">
              <el-date-picker clearable v-model="form.inspectInDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择检定入库日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="安装日期" prop="instDate">
              <el-date-picker clearable v-model="form.instDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择安装日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="拆表日期" prop="rmvDate">
              <el-date-picker clearable v-model="form.rmvDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择拆表日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报废日期" prop="descardDate">
              <el-date-picker clearable v-model="form.descardDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择报废日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="通讯规约" prop="commProtCode">
              <el-input v-model="form.commProtCode" placeholder="请输入通讯规约" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="波特率" prop="baudrateCode">
              <el-input v-model="form.baudrateCode" placeholder="请输入波特率" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否阻逆" prop="ccPreventFlag">
              <el-input v-model="form.ccPreventFlag" placeholder="请输入是否阻逆" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计度器方式" prop="registerMode">
              <el-input v-model="form.registerMode" placeholder="请输入计度器方式" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="建档类型" prop="docTypeCode">
              <el-input v-model="form.docTypeCode" placeholder="请输入建档类型" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电能表技术规范版本" prop="versionNo">
              <el-input v-model="form.versionNo" placeholder="请输入电能表技术规范版本" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电价码" prop="tariffCode">
              <el-input v-model="form.tariffCode" placeholder="请输入电价码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电价名称" prop="tariffName">
              <el-input v-model="form.tariffName" placeholder="请输入电价名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电价金额" prop="tariffAmount">
              <el-input v-model="form.tariffAmount" placeholder="请输入电价金额" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电价版本号" prop="tariffVersionNo">
              <el-input v-model="form.tariffVersionNo" placeholder="请输入电价版本号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预置电费" prop="presetCharge">
              <el-input v-model="form.presetCharge" placeholder="请输入预置电费" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="芯片厂商" prop="chipManufacturer">
              <el-input v-model="form.chipManufacturer" placeholder="请输入芯片厂商" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分拣日期" prop="sortingDate">
              <el-date-picker clearable v-model="form.sortingDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择分拣日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="资金来源" prop="capitalSource">
              <el-input v-model="form.capitalSource" placeholder="请输入资金来源" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盘点时间" prop="checkDate">
              <el-date-picker clearable v-model="form.checkDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择盘点时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="绑定模块条码" prop="moduleCode">
              <el-input v-model="form.moduleCode" placeholder="请输入绑定模块条码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电表费率时段" prop="ratePeriod">
              <el-input v-model="form.ratePeriod" placeholder="请输入电表费率时段" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的电能表数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listMdMeter,
    getMdMeter,
    delMdMeter,
    addMdMeter,
    updateMdMeter
  } from "@/api/meter/mdMeter";
  import {
    selectMdWhInfo,
    selectMdStorageAreaInfo,
    selectMdSaInfo,
    selectStorageLocation
  } from "@/api/meter/mdWhInfo";
  import {
    getToken
  } from "@/utils/auth";
  import {
    jsonMdMeter
  } from "@/api/meter/downloadData"
  import {
    getPc,
    padRight
  } from '@/assets/static/js/dataUtils'
  import '../../../assets/static/js/synWebsocket'

  export default {
    name: "MdMeter",
    dicts: ["emi_meter_sort", "service_status", "md_wiring_mode", "md_volt_code", "md_current_code",
      "md_ap_pre_level_code", "cur_status_code"
    ],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        //上传时遮罩层
        loadToast: false,
        // 电能表表格数据
        mdMeterList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 导入参数
        upload: {
          // 是否显示弹出层
          open: false,
          // 弹出层标题
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/meter/mdMeter/importDataMeter"
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          meterNo: null,
          rfidNo: null,
          sortCode: null,
          typeCode: null,
          curStatusCode: null,
          serviceStatus: null,
          whId: null,
          whAreaId: null,
          storeAreaId: null,
          storeLocId: null,
          wiringMode: null,
          voltCode: null,
          currentCode: null,
          apPreLevelCode: null,
          equipCode: 3301000000270618,
          equipName: null,
        },
        //查询参数库房下拉框
        option: [],
        //查询参数库区下拉框
        options: [],
        //查询参数存放区下拉框
        messageOption: [],
        //查询参数储位下拉框
        storageOption: [],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          rfidNo: [{
            required: true,
            message: '条形码不能为空',
            trigger: 'blur'
          }, {
            // min: 3,
            max: 50,
            message: '长度不得超过50个字符',
            trigger: 'blur'
          }]
        },
        //RFID读卡器定义参数
        ws: null,
        received: null,
        tagData: [],
        connectDialogVisible: false,
        connectFrom: {
          type: "4",
          param: "COM7:115200",
        },
        connectHint: "未连接",
        connectState: false,
        checkAll: false, //天线是否全选
        checkedAnts: [1], //天线初始化的选中
        ants: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ], //天线数据源
        isIndeterminate: true, //全选样式控制
        radioMode: '1', //读取方式
        tagType: '1', //标签类型
        tagCount: 0, //标签数量
        readerCount: 0, //读取总次数
        speed: 0, //读取速率
        time: 0, //读取时间
        isStart: false,
        formLabelWidth: "120px",
        map: {},
        timer: null,
        before: 0,
        after: 0,
        antennaEnable: 1,
        row: null,
        writeEpcVisible: false,
        writeUserVisible: false,
        write6bUserVisible: false,
        writeGbEpcVisible: false,
        writeGbUserVisible: false,
        rfidConfigVisible: false,
        otherConfigVisible: false,
        cusReadEpcVisible: false,
        cusRead6BVisible: false,
        cusReadGbVisible: false,
        cusWriteEpcVisible: false,
        cusWrite6bVisible: false,
        cusWriteGbVisible: false,
        writeForm: {
          epc: null,
          tid: null,
          password: null,
          epcLength: null,
          content: null,
          start: 0,
          gbUser: 48,
        },
        rfidFrom: {
          baseSpeed: null,
          session: null,
          qValue: null,
          inventoryFlag: null,
        },
        otherFrom: {
          onOff: 0 + "",
          intervalTime: 0,
        },
        boxPowerArr: [], //功率ant绑定集合
        selectPowerArr: [], //功率select绑定集合
        boxSelectValues: {}, //功率配置map
        intervalTime: 0,
        intervalOnOff: 0,
        cusReadEpcFrom: {
          epcFilter: false,
          filterWay: 0 + "",
          filterStart: 0,
          filterContent: null,
          tidBox: true,
          tidMode: 1 + "",
          tidLen: 6,
          userBox: true,
          userStart: 0,
          userLen: 6,
          reserveBox: true,
          reserveStart: 0,
          reserveLen: 4,
          passBox: false,
          accessPassword: null,
        },
        cusRead6bFrom: {
          content: 1 + "",
          start: 0,
          byteLen: 10,
          matchingTid: null,
        },
        cusReadGbFrom: {
          gbFilter: false,
          filterWay: -1 + "",
          filterStart: 0,
          filterContent: null,
          tidBox: false,
          tidMode: 0 + "",
          tidLen: 6,
          userBox: false,
          userChild: 48,
          userStart: 4,
          userLen: 6,
          passBox: false,
          password: null,
        },
        cusWriteEpcFrom: {
          epcFilter: false,
          filterWay: 0 + "",
          filterStart: 0,
          accessPassword: null,
          epc: null,
          tid: null,
          userData: null,
          cusWritePane: 1 + "",
          area: 1 + "",
          start: 1,
          content: null,
          blockBox: false,
          blockNumber: 1,
          lockArea: 2 + "",
          lockOperation: 1 + "",
          destroyPassword: null,
        },
        cusWrite6bFrom: {
          tid: null,
          userData: null,
          cusWritePane: 1 + "",
          area: 0 + "",
          start: 8,
          content: null,
          address: null,
          qurAddress: null,
        },
        cusWriteGbFrom: {
          gbFilter: false,
          filterWay: -1 + "",
          filterStart: 0,
          accessPassword: null,
          epc: null,
          tid: null,
          userData: null,
          cusWritePane: 1 + "",
          area: "0x10",
          start: 0,
          content: null,
          lockArea: null,
          lockOperation: null,
        },
      };
    },
    //实例创建后，调用查询函数对页面数据进行查询
    created() {
      this.getList();
      //this.init()
    },
    //以防未正常关闭页面，在退出当前页面时再次进行断开链接操作
    deactivated() {
      //this.disconnect()
    },
    methods: {
      //断开连接
      // disconnect() {
      //   let msg = {
      //     wid: 4,
      //     baseOrApp: 2,
      //     data: {},
      //     msgId: 0x00,
      //   };
      //   this.ws.sendMsg(msg, (res) => {
      //     if (res.result == 0) {
      //       console.log(res.data)
      //       this.connectState = false;
      //       this.connectHint = "未连接";
      //     } else {
      //       console.log(res.data)
      //     }
      //   });
      // },
      // //选择为USB连接时参数
      // usbConnect() {
      //   let msg = {
      //     wid: 4,
      //     baseOrApp: 2,
      //     data: {},
      //     msgId: 0x03,
      //   };
      //   if (this.ws.socket.readyState == 1) {
      //     this.ws.sendMsg(msg, (res) => {
      //       if (res.result == 0) {
      //         if (res.data.length) {
      //           this.connectFrom.param = res.data[0];
      //         } else {
      //           this.connectFrom.param = "未扫描到usbHid设备";
      //           this.$message.error(this.connectFrom.param);
      //         }
      //       } else {
      //         this.$message.error(res.data);
      //       }
      //     })
      //   }
      // },
      // //连接发送读卡器参数
      // connectCardReader() {
      //   let msg = {
      //     wid: 0,
      //     data: this.connectFrom.param,
      //     connectType: this.connectFrom.type
      //   }
      //   if (this.ws.socket.readyState == 1) {
      //     this.ws.sendMsg(msg, (res) => {
      //       if (res.result == 0) {
      //         console.log(res.data)
      //         this.connectState = true;
      //         this.connectHint = this.connectFrom.param + "   Success";
      //       } else {
      //         console.log(res.data)
      //         this.connectState = false;
      //         this.connectHint = this.connectFrom.param + "   Fail";
      //       }
      //     })
      //   }
      // },
      // //对读卡器相关进行实例化创建
      // init() {
      //   var WS = require('../../../assets/static/js/synWebsocket')
      //   // this.ws = new WS("ws://192.168.11.124:9090/rfidService/1234");
      //   this.ws = new WS("ws://127.0.0.1:9090/rfidService/1234");

      //   this.ws.onOpen = (e) => {
      //     console.log("webSocket连接成功")
      //   };
      //   this.ws.onClose = (e) => {
      //     console.log("webSocket连接关闭");
      //   };
      //   this.ws.onError = (e) => {
      //     // console.log(e);
      //   };
      //   this.ws.handlerTagEpcLog = (res) => {
      //     this.pooled6c(res.data);
      //     this.writeForm.tid = res.data.tid
      //   };
      //   this.ws.handlerTag6bLog = (res) => {
      //     this.pooled6b(res.data);
      //   };
      //   this.ws.handlerTagGbLog = (res) => {
      //     this.pooledGb(res.data);
      //   };
      //   this.ws.handlerTcpDisconnected = (res) => {
      //     console.log(res.data);
      //   };
      //   this.ws.handlerGpiStart = (res) => {
      //     console.log(res.data);
      //   };
      //   this.ws.handlerGpiOver = (res) => {
      //     console.log(res.data);
      //   };
      // },
      /** 查询电能表列表 */
      getList() {
        this.loading = true;
        listMdMeter(this.queryParams).then(response => {
          this.mdMeterList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
        selectMdWhInfo().then(response => {
          this.option = response.data
          this.whIdChange()
        })
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
       // this.disconnect()
      },
      // 表单重置
      reset() {
        this.form = {
          meterId: null,
          meterNo: null,
          rfidNo: null,
          sealNo: null,
          madeNo: null,
          sortCode: null,
          typeCode: null,
          modelCode: null,
          meterAddress: null,
          voltCode: null,
          currentCode: null,
          apPreLevelCode: null,
          rpPreLevelCode: null,
          bothWayCalc: null,
          wiringMode: null,
          meterDigits: null,
          curStatusCode: null,
          belongDept: null,
          prOrg: null,
          areaCode: null,
          prCode: null,
          manufacturer: null,
          lotNo: null,
          deliveryDate: null,
          createdDate: null,
          inspectInDate: null,
          instDate: null,
          rmvDate: null,
          descardDate: null,
          commProtCode: null,
          baudrateCode: null,
          ccPreventFlag: null,
          registerMode: null,
          docTypeCode: null,
          versionNo: null,
          whId: null,
          whAreaId: null,
          storeAreaId: null,
          storeLocId: null,
          tariffCode: null,
          tariffName: null,
          tariffAmount: null,
          tariffVersionNo: null,
          presetCharge: null,
          orderType: null,
          chipManufacturer: null,
          sortingDate: null,
          capitalSource: null,
          checkDate: null,
          moduleCode: null,
          ratePeriod: null,
          equipCode: 3301000000270618,
          equipName: 'A级单相智能电能表双方向居民1日',

        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.meterId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        //this.form.sortCode = "01"
        this.title = "添加电能表";
        // setTimeout(() => {
        //   this.usbConnect()
        // }, 100);
        // setTimeout(() => {
        //   this.connectCardReader()
        // }, 500);
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const meterId = row.meterId || this.ids
        getMdMeter(meterId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改电能表";
        });
        // setTimeout(() => {
        //   this.usbConnect()
        // }, 100);
        // setTimeout(() => {
        //   this.connectCardReader()
        // }, 500);
      },
      /** 提交按钮 */
      submitForm() {
        if (this.title == "修改电能表") {
          this.$refs["form"].validate(valid => {
            if (valid) {
              updateMdMeter(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }
          })
        } else {
          this.$refs["form"].validate(valid => {
            if (valid) {
              addMdMeter(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          })
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const meterIds = row.meterId || this.ids;
        this.$modal.confirm('是否确认删除电能表编号为"' + meterIds + '"的数据项？').then(function() {
          return delMdMeter(meterIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('meter/mdMeter/export', {
          ...this.queryParams
        }, `mdMeter_${new Date().getTime()}.xlsx`)
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "数据导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download('meter/mdMeter/importTemplateMeter', {}, `电能表导入模板.xlsx`)
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.loadToast = true
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response
          .msg + "</div>", "导入结果", {
            dangerouslyUseHTMLString: true
          });
        if (response.code == "200") {
          this.loadToast = false
        }
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      //下载数据按钮
      downloadData() {
        if (this.ids.length == 0) {
          let array = [];
          let queryParams = {
            meterIds: array
          }
          this.$confirm('此操作将下载所有文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            jsonMdMeter(queryParams).then(response => {
              if (response.code == 200) {
                this.$message({
                  message: `数据成功下载至${response.msg}中`,
                  type: 'success'
                });
              } else {
                this.$message.error('数据下载失败');
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消下载'
            });
          });
        } else {
          let queryParams = {
            meterIds: JSON.parse(JSON.stringify(this.ids))
          }
          jsonMdMeter(queryParams).then(response => {
            if (response.code == 200) {
              this.$message({
                message: `数据成功下载至${response.msg}中`,
                type: 'success'
              });
            } else {
              this.$message.error('数据下载失败');
            }
          })
        }
      },
      //读卡按钮操作
      cardReading() {
        this.clean();
        let msg = {
          wid: 4,
          baseOrApp: 0,
          data: {
            antennaEnable: 1,
            inventoryMode: parseInt(0),
            readTid: {
              mode: 0,
              len: 6,
            }
          },
          msgId: 0x10,
        };
        this.ws.sendMsg(msg, (res) => {
          if (res.result == 0) {
            this.isStart = true;
            this.flushTable();
          } else {
            this.$message.error(res.data);
          }
        });
        //一秒后关闭读取操作
        setTimeout(() => {
          this.pause()
        }, 1000)
      },
      //清除事件
      clean() {
        this.map = {};
        this.tagData = [];
        this.tagCount = 0;
        this.readerCount = 0;
        this.speed = 0;
        this.time = 0;
        this.row = null;
        // console.log(this.map);
      },
      //对条形码进行渲染
      flushTable() {
        this.timer = setInterval(() => {
          this.tagData.splice(0, this.tagData.length);
          let readCount = 0;
          this.before = this.after;
          for (let key in this.map) {
            let value = this.map[key];
            this.tagData.push(value);
            readCount += value.count;
          }
          this.tagCount = Object.keys(this.map).length;
          this.readerCount = readCount;
          this.after = this.readerCount;
          if (this.after >= this.before) {
            this.speed = this.after - this.before;
          }
          this.form.rfidNo = this.tagData[0].epc
          this.time++;
        }, 100);
      },
      //停止读取操作
      pause() {
        let msg = {
          wid: 4,
          baseOrApp: 0,
          data: {},
          msgId: 0xFF,
        };
        this.ws.sendMsg(msg, (res) => {
          if (res.result == 0) {
            console.log(res.data)
            this.isStart = false;
            clearInterval(this.timer);
          } else {
            console.log(res.data)
          }
        });
      },
      //写卡操作
      writeCard() {
        let msg = {
          wid: 4,
          baseOrApp: 0,
          data: {
            antennaEnable: 1,
            area: 1,
            start: 1,
            hexPassword: null,
            hexWriteData: getPc(this.form.rfidNo) + padRight(this.form.rfidNo, 4),
          },
          msgId: 0x11,
        };
        if (this.writeForm.tid) { //如果TID不为null则匹配写
          msg.data.filter = {
            area: 2,
            bitStart: 0,
            bitLength: this.writeForm.tid.length * 4,
            hexData: this.writeForm.tid //'E28011052000785C6FC50979'
          }
        }
        this.ws.sendMsg(msg, res => {
          if (res.result == 0) {
            this.$message.success("写卡成功");
            console.log(res.data)
          } else {
            this.$message.error(`写卡失败,${res.data}`)
            console.log(res.data)
          }
        });
      },
      //对读取内容进行去重
      pooled6c(data) {
        if (!Array.isArray(data)) {
          if (data.epc + data.tid in this.map) {
            let count = this.map[data.epc + data.tid]["count"];
            let ant1 = this.map[data.epc + data.tid]["ant1"];
            count++;
            this.map[data.epc + data.tid]["count"] = count;
            this.map[data.epc + data.tid]["rssi"] = data.rssi;
            switch (data.antId) {
              case 1:
                ant1++;
                this.map[data.epc + data.tid]["ant1"] = ant1;
                break;
              default:
                break;
            }
          } else {
            this.map[data.epc + data.tid] = {
              type: "6C",
              epc: data.epc,
              tid: data.tid,
              userdata: data.userdata != undefined ? data.userdata : null,
              reserved: data.reserved != undefined ? data.reserved : null,
              rssi: data.rssi,
              ant1: data.antId == 1 ? 1 : 0,
              count: 1,
            }
          }
        } else {
          for (let i = 0; i < data.length; i++) {
            if (data[i].epc + data[i].tid in this.map) {
              let count = this.map[data[i].epc + data[i].tid]["count"];
              let ant1 = this.map[data[i].epc + data[i].tid]["ant1"];
              count++;
              this.map[data[i].epc + data[i].tid]["count"] = count;
              this.map[data[i].epc + data[i].tid]["rssi"] = data[i].rssi;
              switch (data[i].antId) {
                case 1:
                  ant1++;
                  this.map[data[i].epc + data[i].tid]["ant1"] = ant1;
                  break;
                default:
                  break;
              }
            } else {
              this.map[data[i].epc + data[i].tid] = {
                type: "6C",
                epc: data[i].epc,
                tid: data[i].tid,
                userdata: data[i].userdata != undefined ? data[i].userdata : null,
                reserved: data[i].reserved != undefined ? data[i].reserved : null,
                rssi: data[i].rssi,
                ant1: data[i].antId == 1 ? 1 : 0,
                count: 1,
              }
            }
          }
        }
      },
      //库房下拉框改变事件
      whIdChange() {
        let querySelsctParams = {}
        let option = JSON.parse(JSON.stringify(this.option))
        querySelsctParams.whId = option[0].value
        selectMdStorageAreaInfo(querySelsctParams).then(response => {
          this.options = response.data
        })
      },
      //库区下拉框改变事件
      whAreaIdChange() {
        let queryMdOptionsParams = {}
        let option = JSON.parse(JSON.stringify(this.option))
        queryMdOptionsParams.whId = option[0].value
        queryMdOptionsParams.whAreaId = this.queryParams.whAreaId
        this.queryParams.storeAreaId = null
        this.queryParams.storeLocId = null;
        this.storageOption = []
        selectMdSaInfo(queryMdOptionsParams).then(response => {
          this.messageOption = response.data
        })
      },
      //存放区下拉框改变事件
      storeAreaIdChange() {
        let queryParams = {}
        let option = JSON.parse(JSON.stringify(this.option))
        queryParams.whId = option[0].value
        queryParams.whAreaId = this.queryParams.whAreaId
        queryParams.storeAreaId = this.queryParams.storeAreaId
        this.queryParams.storeLocId = null;
        selectStorageLocation(queryParams).then(response => {
          this.storageOption = response.data
        })
      }
    }
  };
</script>
